package leetcode.recursive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//17. 电话号码的字母组合
public class LetterCombinations {

    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if (digits.length() == 0) {
            return res;
        }
        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        blacktrace(res, phoneMap, digits, 0, new StringBuffer());
        return res;
    }

    private void blacktrace(List<String> res, Map<Character,
            String> phoneMap, String digits, int start,
                            StringBuffer stringBuffer) {
        if (start == digits.length()) {
            res.add(stringBuffer.toString());
            return;
        }
        String letters = phoneMap.get(digits.charAt(start));
        int length = letters.length();
        for (int i = 0; i < length; i++) {
            stringBuffer.append(letters.charAt(i));
            blacktrace(res, phoneMap, digits, start + 1, stringBuffer);
            stringBuffer.deleteCharAt(start);
        }
    }


    public List<String> letterCombinations2(String digits) {
        List<String> res = new ArrayList<>();
        if (digits.length() == 0) {
            return res;
        }
        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        StringBuffer stringBuffer = new StringBuffer();
        backtracing(phoneMap, res, digits, 0, digits.length(), stringBuffer);
        return res;
    }

    private void backtracing(Map<Character, String> phoneMap,
                             List<String> res, String digits,
                             int start, int n,
                             StringBuffer stringBuffer) {
        if (start == n) {
            res.add(new String(stringBuffer));
            return;
        }
        String s = phoneMap.get(digits.charAt(start));
        for (int i = 0; i < s.length(); i++) {
            stringBuffer.append(s.charAt(i));
            backtracing(phoneMap, res, digits, start + 1, n, stringBuffer);
            // 回溯
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        }
    }
}
